﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Syndication;
using PBDesk.com.Extension.UmbHelper;
using System.Xml;
using Umbraco.Framework.Persistence.Model.IO;
using PBDesk.Utilities;
using System.Xml.Linq;

namespace PBDesk.com.Extension.FeedsAggregator
{
    public class FileOpHelper
    {
        internal static void WriteFeedToFile(string fileName, SyndicationFeed feed)
        {
            if (feed != null && fileName.IsNotNullAndNotEmpty())
            {
                try
                {
                    string fullPath = MyUmb.CacheFilesLoc + fileName;
                    using (var w = XmlWriter.Create(System.IO.File.Create(fullPath)))
                    {
                        feed.SaveAsRss20(w);
                        w.Flush();
                        w.Close();
                        w.Kill();
                    }
                    //XmlTextWriter t = new XmlTextWriter(fullPath, Encoding.UTF8);
                    //t.Namespaces = true;
                    //feed.SaveAsRss20(t);
                    //t.Flush();
                    //t.Close();
                    //t.Kill();
                }
                catch (Exception ex)
                {
                    MyLog.WriteErr<FileOpHelper>("Error in FileOpHelper::WriteFeedToFile() while writing feed to file", ex);
                    
                }
            }
            else
            {
                MyLog.Write<FileOpHelper>("FileOpHelper::UpdateNewsFeedCache", "Feed cache not generated as feed object is null or not a valid filename.");
            }
        }

        internal static XDocument GetXMLFile(string fileName)
        {
            XDocument xDoc = null;
            try
            {
                if (fileName.IsNotNullAndNotEmpty())
                {
                    try
                    {
                        xDoc = XDocument.Load(fileName);
                    }
                    catch (Exception ex1)
                    {
                        throw new Exception("Error at SyndicationHelper.GetXMLResource() while parsing/loading XML from " + fileName, ex1);
                    }
                }
                else
                {
                    throw new ArgumentNullException("fileName", "Parameter fileName is null or empty.");
                }
            }
            catch (Exception ex)
            {
                MyLog.WriteErr<FileOpHelper>("Error in GetXMLFile()", ex);
            }
            return xDoc;
        }
    }
}